package zjw.springboot2.test.controller;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

//@Component
//@ServerEndpoint("/websocketurl")//设置websocket连接url，就是前端创建websocket需要提供的url
public class MyWebSocketService2 {
    private Session session;
    
    //存放所有的websocket连接
    private static CopyOnWriteArraySet<MyWebSocketService2> myWebSocketServicesSet = new CopyOnWriteArraySet<>();
    
    //建立websocket连接时自动调用
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        myWebSocketServicesSet.add(this);
        System.out.println("有新的websocket连接进入，当前连接总数为" + myWebSocketServicesSet.size());
    }
 
    //关闭websocket连接时自动调用
    @OnClose
    public void onClose(){
        myWebSocketServicesSet.remove(this);
        System.out.println("连接断开，当前连接总数为" + myWebSocketServicesSet.size());
    }
 
    //websocket接收到消息时自动调用
    @OnMessage
    public void onMessage(String message){
        System.out.println("this：" + message);
    }
 
    //通过websocket发送消息
    public void sendMessage(String message){
        for (MyWebSocketService2 webSocketService : myWebSocketServicesSet){
            try {
                webSocketService.session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                System.err.println(this + "发送消息错误:" + e.getClass() + ":" + e.getMessage());
            }
        }
    }
}